package io.filecopy;

import java.util.LinkedList;
import java.util.Queue;

public class FileSystemTaskListImpl implements FileSystemTaskList {

  private boolean completelyPrepared;

  public void setCompletelyPrepared() {
    synchronized (tasks) {
      this.completelyPrepared = true;
      tasks.notifyAll();
    }
  }

  public FileSystemTaskListImpl() {
    this.completelyPrepared = false;
    this.tasks = new LinkedList<FileSystemTask>();
  }

  private Queue<FileSystemTask> tasks;

  @Override
  public FileSystemTask getNextTask() throws InterruptedException {
    synchronized (tasks) {
      while (!completelyPrepared && tasks.isEmpty()) {
        tasks.wait();
      }
      if (!tasks.isEmpty()) {
        return tasks.poll();
      } else {
        return null;
      }
    }
  }

  public void addTask(final FileSystemTask task) {
    synchronized (tasks) {
      tasks.add(task);
      tasks.notifyAll();
    }
  }

  @Override
  public boolean hasMoreTasks() throws InterruptedException {
    synchronized (tasks) {
      while (!completelyPrepared && tasks.isEmpty()) {
        System.out.println("sleep");
        tasks.wait();
        System.out.println("awake");
      }
      return !completelyPrepared || !tasks.isEmpty();
    }
  }

  public boolean isCompletelyPrepared() {
    return completelyPrepared;
  }
}